#include "reader.h"


std::string unicode_to_utf8(const std::wstring& wstr)
{
    std::string ret;
    std::wstring_convert<std::codecvt_utf8<wchar_t>> wcv;
    ret = wcv.to_bytes(wstr);
    return ret;
}
std::wstring utf8_to_unicode(const std::string& str)
{
    std::wstring ret;
    std::wstring_convert<std::codecvt_utf8<wchar_t>> wcv;
    ret = wcv.from_bytes(str);
    return ret;
}
std::string unicode_to_ansi(const std::wstring& wstr)
{
    std::string ret;
    std::mbstate_t state = {};
    const wchar_t* src = wstr.data();
    size_t len = std::wcsrtombs(nullptr, &src, 0, &state);
    if (static_cast<size_t>(-1) != len) {
        std::unique_ptr<char[]> buff(new char[len + 1]);
        len = std::wcsrtombs(buff.get(), &src, len, &state);
        if (static_cast<size_t>(-1) != len) {
            ret.assign(buff.get(), len);
        }
    }
    return ret;
}
std::wstring ansi_to_unicode(const std::string& str)
{
    std::wstring ret;
    std::mbstate_t state = {};
    const char* src = str.data();
    size_t len = std::mbsrtowcs(nullptr, &src, 0, &state);
    if (static_cast<size_t>(-1) != len) {
        std::unique_ptr<wchar_t[]> buff(new wchar_t[len + 1]);
        len = std::mbsrtowcs(buff.get(), &src, len, &state);
        if (static_cast<size_t>(-1) != len) {
            ret.assign(buff.get(), len);
        }
    }
    return ret;
}
std::string utf8_to_ansi(const std::string& str)
{
    return unicode_to_ansi(utf8_to_unicode(str));
}
std::string ansi_to_utf8(const std::string& str)
{
    return unicode_to_utf8(ansi_to_unicode(str));
}


std::string file_reader(std::string file_name)
{
    clock_t start = clock();
    std::ifstream file;
    std::string file_content;

    file.open(file_name);
    if (!file.is_open()) {
        std::clog << "[Error]\t\t Cannot read the file \"" << file_name << "\"." << std::endl;
        exit(1);
    }

    std::string temporary;
    while (std::getline(file, temporary)) {
        file_content += utf8_to_ansi(temporary) + "\n";
    }

    clock_t end = clock();

    std::clog << "[Reader]\t Complete read the file \"" << file_name << "\" ";
    std::clog << "in " << (end - start) << "ms." << std::endl;
    return (file_content);
}